package org.itboys.admin.service.lasted;

import org.apache.commons.collections.map.HashedMap;
import org.itboys.admin.common.ExceptionEnum;
import org.itboys.admin.entity.lasted.SundayArea;
import org.itboys.admin.entity.lasted.SystemEmployee;
import org.itboys.admin.entity.lasted.SystemUser;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.NumberUtil;
import org.itboys.commons.utils.PhoneUtil;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author：贾琦磊
 * @Date：2018/9/6
 * @Description：
 */
@Service
public class SystemEmployeeService extends BaseMongoService<SystemEmployee>{
    private static final String PREFIX="E";
    @Autowired
    private SundayUploadService uploadService;
    @Resource(name = "mobileDs")
    private MongoDataSource dataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return dataSource;
    }
    @Override
    protected Class<SystemEmployee> getEntityClass() {
        return SystemEmployee.class;
    }

    @Autowired
    private SystemUserService userService;


    public PageResult<SystemEmployee> select(HttpServletRequest request){
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request);
        Map<String, String> vagueParam = ParamUtil.packageMongoVagueParam(request, "name");
        param.put("isDeleted", CommonConstants.NO);
        PageResult<SystemEmployee> result = super.containpageQuery(request, vagueParam, param);
        return result;
    }

    public void save(Long id,SystemEmployee employee){
        if(!PhoneUtil.isMobileNumber(employee.getMobile())){
            throw new ErrorException("手机号格式错误");
        }
        if(LongUtil.isNotZreo(id)){
            super.updateExceptEmpty(id,employee);
        }else {
            employee.setNumber( NumberUtil.generateNumber(PREFIX));
            super.save(employee);
        }
    }
    @Override
    public void delete(Long id){
        Map<String,Object> param=new HashedMap();
        param.put("isDeleted", CommonConstants.NO);
        param.put("employeeId",id);
        List<SystemUser> users = userService.list(param);
        if(ListUtil.isNotNull(users)){
            throw new ErrorException(ExceptionEnum.DELETE_EMP_EXCPTION.getValue());
        }
        super.delete(id);
    }
}
